<?php

namespace App\Controller\Admin;

use App\Controller\AbstractController;
use App\Kernel\Util\JwtInstance;
use App\Service\SysService;
use Hyperf\Di\Annotation\Inject;

class UserController extends AbstractController
{
    /**
     * @Inject()
     * @var SysService
     */
    protected $sysService;

    public function bing()
    {

        $str=file_get_contents('https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1');
        $res = json_decode($str);
        if(empty($res->images[0]->url)){
            $imgurl = '';
        }else{
            $imgurl = 'http://s.cn.bing.net'.$res->images[0]->url;
        }
        return $this->response->success('登录背景图', [
            'src' => $imgurl
        ]);
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $username = (string)$this->request->input('username');
        $password = (string)$this->request->input('password');

        try {
            $user = $this->sysService->login($username, $password);
            $token = JwtInstance::instance()->encode($user);
            return $this->response->success('登录成功', [
                'token' => $token,
                'expire' => config('sys_token_exp')
            ]);

        } catch (\Exception $e) {
            return $this->response->error($e->getMessage());
        }
    }

    public function userInfo()
    {
        try {
            $userId = JwtInstance::instance()->build()->getId();
            $model = $this->sysService->getUserData($userId);
            return $this->response->success('获取用户信息', [
                'id'=>$model->id,
                'username' => $model->username,
                'nickname' => $model->nickname
                ]);
        }catch (\Exception $e) {
            return $this->response->error($e->getMessage());
        }

    }
}